<?php
/**
 * User: Niuxitong
 * Date: 2021/1/6 20:03
 */
namespace app\admin\model;

use app\common\controller\Callfunc;
use think\Log;
use think\Model;
use think\Db;
use think\Cache;
use think\Session;

class Conference extends Model
{
    // 表名
    protected $table = 'conference';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'repeat_text',
        'meetingType_text',
        'status_text'
    ];


    /**
     *  获取加密地址
     * @param $cid
     * @param $host
     * @param $scheme
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getEncryptedExtranet($cid, $host, $scheme){
        // 获取缓存中的剩余服务器
        $user = Db::name('admin')->alias('admin')
            ->join("conference conf","conf.admin_id = admin.id")
            ->where("conf.serial",$cid)
            ->find();
        if (!$user['admin_tag']){
            $user['admin_tag'] = "null";
            $user['validity_time'] = "2000-01-01 00:00:00";
        }
        // 缓存类型，如果配置了redis，就走redis，如果没有就走本地文件  //Cache::store() 此方法会自动切换本地文件缓存，或者是redis缓存。
        $cacheType = config('cache.redis') ? 'redis' : '';
        $allServerAddress = Cache::store($cacheType)->get(config('redis_prefix').'ServerAddress'."-admin_tag-".$user['admin_tag']);

        //如果媒体服务器缓存中不存， 就查询数据库并缓存
        //获取所有媒体服务器列表
        if (!$allServerAddress) {
            $serverAddressObj = new \app\admin\model\ServerAddress;
            $allServerAddress = [];
//            $serverAddressSQLdata = $serverAddressObj->select();
            $user_tags_service = Db::name('server_grouping')->whereLike("tag_ids",'%'.$user['admin_tag'].'%')->find();
            $serverAddressSQLdata = $serverAddressObj->where("distinguish",$user_tags_service['id'])->select();
            if (!$serverAddressSQLdata){
                $serverAddressSQLdata = $serverAddressObj->where('distinguish is null')->select();
            }
            foreach ($serverAddressSQLdata as $sqldata) {
                $addressInfo = [];
                $addressInfo["intranet_address"] = $sqldata['intranet_address'];
                $addressInfo["external_address"] = $sqldata["external_address"];
                $addressInfo["encrypted_extranet"] = $sqldata["encrypted_extranet"];
                $addressInfo["encrypted_intrane"] = $sqldata["encrypted_intrane"];
                $allServerAddress[] = $addressInfo;
            }
        }

        // 查询会议ID是否已分配会议地址
        $ConfServerAddress = Cache::store($cacheType)->get(config('redis_prefix').'ConfServerAddress:' . $cid);
        if ($ConfServerAddress) {
            $seradd = $ConfServerAddress;
        } else {
            $seradd = array_shift($allServerAddress);  //使用一个删除一个。
            Cache::store($cacheType)->set(config('redis_prefix').'ConfServerAddress:' . $cid, $seradd, 0);
            Cache::store($cacheType)->set(config('redis_prefix').'ServerAddress'."-admin_tag-".$user['admin_tag'], $allServerAddress, 0);
        }

        //根据用户使用的是https 还是http还是什么都没有
        if ($scheme == "https") {
            $encrypted = 1;
        } elseif ($scheme == "http") {
            $encrypted = 0;
        } else {
            $encrypted = 1;
        }
        if ($encrypted) {   //如果是https 走加密
            $encryptedIntrane = explode(":", $seradd['encrypted_intrane']);
            $encryptedIntrane = $encryptedIntrane[1];
            $encryptedIntrane = explode("//", $encryptedIntrane);
            $encryptedIntrane = $encryptedIntrane[1];

            $encryptedExtranet = explode(":", $seradd['encrypted_extranet']);
            $encryptedExtranet = $encryptedExtranet[1];
            $encryptedExtranet = explode("//", $encryptedExtranet);
            $encryptedExtranet = $encryptedExtranet[1];
            if ($host == $encryptedExtranet) {
                $addressInfo = $seradd['encrypted_extranet'];
            } elseif ($host == $encryptedIntrane) {
                $addressInfo = $seradd['encrypted_intrane'];
            } else {
                $addressInfo = $seradd['encrypted_extranet'];
            }
        } else {  //不加密
            $intranetAddress = explode(":", $seradd['intranet_address']);
            $intranetAddress = $intranetAddress[1];
            $intranetAddress = explode("//", $intranetAddress);
            $intranetAddress = $intranetAddress[1];

            $externalAddress = explode(":", $seradd['external_address']);
            $externalAddress = $externalAddress[1];
            $externalAddress = explode("//", $externalAddress);
            $externalAddress = $externalAddress[1];
            if ($host == $intranetAddress) {
                $addressInfo = $seradd['intranet_address'];
            } elseif ($host == $externalAddress) {
                $addressInfo = $seradd['external_address'];
            } else {
                $addressInfo = $seradd['external_address'];
            }
        }
        $encrypted_extranet = trim($addressInfo, '/').'/';   //防止后台输入时已经填写了 /或者没有填写/。 这里先过滤掉再拼接上
        // 获取缓存中的剩余服务器
        return $encrypted_extranet;
    }

    /*
     * 获取后台永不失效的token用于后台分享使用的链接之中
     */
    public function getUserToken($user_id, $token) {
        $info = Db::name('user_token')->where(['user_id'=>$user_id, 'expiretime'=>0])->field('tokenbu')->find();
        if (empty($info)) {
            //没有获取到永不失效的token，可能是执行过登出所有设备或更新后暂未重新登录
            $config = \think\Config::get('token');
           // $encryptedToken = hash_hmac($config['hashalgo'], $token, $config['key']);
            $encryptedToken = hash_hmac($config['hashalgo'], time(), $config['key']);       //改写，解决user_token表中token字段相同的bug
            Db::name('user_token')->insert([
                'token'      => $encryptedToken,
                'user_id'    => $user_id,
                'createtime' => time(),
                'expiretime' => 0,
                'tokenbu'    => $token
            ]);
            return $token;
        }else{
            return $info['tokenbu'];
        }
    }
    
    //同步创建会议
    //逻辑也写到此方法中
    // 具体参考 vymeet项目的 api/controller/Conference.php
    /**
     * @param $admin_id 用户id 必须
     * @param array $params  传来的活动相关的参数
     *
     * 请按创建活动时 相关的数据替换这里写死的。 没有的就用这里的默认值
     *
     */
    public function addConference($params = [],$tag = false)
    {
        $data = [];
        $data['serial'] = $params['serial'];    //--- 必须
        $data['name'] = $params['name'];        //--- 必须
        $data['from_tag'] = 2;                  //--- 创建来源， 1：vymeet平台  2:onzoom平台
        $data['admin_id'] = $params['admin_id'];
        $data['company_id'] = 0;              //TODO  活动平台不支持 企业id
        $data['mainPassword'] = isset($params['mainPassword']) ? $params['mainPassword'] : 'abcd';
        $data['normalPassword'] = isset($params['normalPassword']) ? $params['normalPassword'] : '';
        //是否是个人会议 0：否 1：是
        $data['isself'] = 0;

        //会议详情（verchar类型255）
        $data['detail'] = isset($params['summary']) ? $params['summary'] : "";    //同步活动简介
        //meetingType   会议类型:0=普通会议,1=重要会议
        $data['meetingType'] = 0;

        //参会人员
        $participantsList = isset($params['attendee']) ? json_decode($params['attendee']) : [];

        //重复类型 周期会议(单选):n=不重复,d=每天,w=每周,s=每两周,m=每月
        $repeat = isset($params['repeat']) ? $params['repeat'] : 'n';
        $data['repeat'] = $repeat;

        //会议选项 主持人音频:0=关闭,1=开启
        $data['mainAudio'] = isset($params['mainAudio']) ? (int)$params['mainAudio'] : 1;
        //主持人视频:0=关闭,1=开启
        $data['mainVideo'] = isset($params['mainVideo']) ? (int)$params['mainVideo'] : 1;
        //参与者视频:0=关闭,1=开启
        $data['participantVideo'] = isset($params['participantVideo']) ? (int)$params['participantVideo'] : 1;
        //参与者音频:0=关闭,1=开启
        $data['participantAudio'] = isset($params['participantAudio']) ? (int)$params['participantAudio'] : 1;

        //会议选项(json格式)
        $params['onlyParticipants'] = isset($params['onlyParticipants']) ? (int)$params['onlyParticipants'] : 0;
        $params['callParticipants'] = isset($params['callParticipants']) ? (int)$params['callParticipants'] : 0;
        $params['callEquipment'] = isset($params['callEquipment']) ? (int)$params['callEquipment'] : 0;
        $option = array(
            "onlyParticipants" => $params['onlyParticipants'],
            "callParticipants" => $params['callParticipants'],
            "callEquipment" => $params['callEquipment'],
        );
        $data['option'] = json_encode($option);
        unset($params['onlyParticipants']);
        unset($params['callParticipants']);
        unset($params['callEquipment']);

        //会议模式  会议模式:freeCamera=自由视角,mainBroadcast=与主持人广播视频一致,mainCamera=与主持人视角一致,intercom:对讲模式,voiceSeminar:语音讨论会议,trainingConference:在线培训会议,EHSfieldOperation:EHS现场作业,multilingualTranslation:多语言翻译
        $data['mode'] = 'freeCamera';

        //设备  会议状态:0=未锁定,1=锁定
        $data['lock'] = 0;
        $newTime = time();
        $data['createTime'] = date("Y-m-d H:i:s", $newTime);
        $data['startTime'] = date("Y-m-d H:i:s", $newTime);
        $data['endTime'] = '2030-01-01 00:00:00';   //这里先按长期会议算
        $data['lock'] = 0;
        if($tag){
            $r = Db::name('conference')->where('serial',$params['serial'])->where('from_tag',2)->count();
            if($r > 0){
               // $data['startTime'] = $params['startTime'];
                $result = $this->where('serial',$params['serial'])->where('from_tag',2)->update($data);
            }else{
               // $data['startTime'] = params['startTime'];
                $result = $this->insert($data);
            }
        }else{
            $result = $this->insert($data);
        }
        return $result;
    }



    public function addConference888($admin_id, $params = [])
    {
        $data = [];
        $params['serial'] = Callfunc::makeUuid();     //---  生成唯一识别码
        $data['serial'] = $params['serial'];            //--- 必须
        $data['name'] = $params['title'];               //--- 必须
        $data['from_tag'] = 2;                          //--- 创建来源， 1：vymeet平台  2:onzoom平台

        $data['admin_id'] = $admin_id;
        $data['company_id'] = $admin_id;                //TODO  活动平台不支持 企业id
        $data['mainPassword'] = isset($params['mainPassword']) ? $params['mainPassword'] : 'abcd';
        $data['normalPassword'] = isset($params['normalPassword']) ? $params['normalPassword'] : '';
        //是否是个人会议 0：否 1：是
        $data['isself'] = 0;

        //会议详情（verchar类型255）
        $data['detail'] = isset($params['detail']) ? $params['detail'] : "";
        //meetingType   会议类型:0=普通会议,1=重要会议
        $data['meetingType'] = 0;

        //参会人员
        $participantsList = isset($params['attendee']) ? json_decode($params['attendee']) : [];

        //重复类型 周期会议(单选):n=不重复,d=每天,w=每周,s=每两周,m=每月
        $repeat = isset($params['repeat']) ? $params['repeat'] : 'n';
        $data['repeat'] = $repeat;

        //会议选项 主持人音频:0=关闭,1=开启
        $data['mainAudio'] = isset($params['mainAudio']) ? (int)$params['mainAudio'] : 1;
        //主持人视频:0=关闭,1=开启
        $data['mainVideo'] = isset($params['mainVideo']) ? (int)$params['mainVideo'] : 1;
        //参与者视频:0=关闭,1=开启
        $data['participantVideo'] = isset($params['participantVideo']) ? (int)$params['participantVideo'] : 1;
        //参与者音频:0=关闭,1=开启
        $data['participantAudio'] = isset($params['participantAudio']) ? (int)$params['participantAudio'] : 1;

        //会议选项(json格式)
        $params['onlyParticipants'] = isset($params['onlyParticipants']) ? (int)$params['onlyParticipants'] : 0;
        $params['callParticipants'] = isset($params['callParticipants']) ? (int)$params['callParticipants'] : 0;
        $params['callEquipment'] = isset($params['callEquipment']) ? (int)$params['callEquipment'] : 0;
        $option = array(
            "onlyParticipants" => $params['onlyParticipants'],
            "callParticipants" => $params['callParticipants'],
            "callEquipment" => $params['callEquipment'],
        );
        $data['option'] = json_encode($option);
        unset($params['onlyParticipants']);
        unset($params['callParticipants']);
        unset($params['callEquipment']);

        //会议模式  会议模式:freeCamera=自由视角,mainBroadcast=与主持人广播视频一致,mainCamera=与主持人视角一致,intercom:对讲模式,voiceSeminar:语音讨论会议,trainingConference:在线培训会议,EHSfieldOperation:EHS现场作业,multilingualTranslation:多语言翻译
        $data['mode'] = 'freeCamera';


        //设备  会议状态:0=未锁定,1=锁定
        $data['lock'] = 0;
        $newTime = time();
        $data['createTime'] = date("Y-m-d H:i:s", $newTime);
        $data['startTime'] = date("Y-m-d H:i:s", $newTime);
        $data['endTime'] = '2030-01-01 00:00:00';   //这里先按长期会议算
        $data['lock'] = 0;

        $result = $this->insert($data);
        return $repeat;


    }












}